// stores/cart.ts
import { defineStore } from 'pinia'
import { clearCarts, deleteCarts } from "../api/goods.ts";
import { Modal } from "ant-design-vue";
import { Session } from '../utils/storage.ts';
import { getFavoriteList } from "@/api/goods";
import { getToken } from '@/utils/auth';
type CartItem = {
  id: string | number
  name: string
  price: number
  color?: string
  size: string
  qty: number,
  favorite: boolean,
}
type ViewHistoryItem = Omit<CartItem, 'qty' | 'favorite'> & {
  viewedAt: number // 添加浏览时间戳
}
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [] as CartItem[],
    detailDataItems: [] as ViewHistoryItem[],
    goods: [],
    shopCartList: [] as any[],
    collectList: [] as any[],
  }),

  actions: {
    setShopCart(chartList: any) {
      this.shopCartList = chartList;
      Session.set('cartList', chartList)
    },

    getShopCart() {
      return Session.get('cartList') || null
    },

    setCollect(chartList: any) {
      this.shopCartList = chartList;
      Session.set('collectList', chartList)
    },

    async getCollect() {
      if(!getToken()) {
        return null
      }
      const favoriteResDel = await getFavoriteList()
      if (favoriteResDel.code === 200) {
        Session.set('collectList', favoriteResDel.result.data)
      }
      return Session.get('collectList') || null
    },




    addItem(item: CartItem) {
      this.items.push(item)
    },
    //添加浏览
    addDetailDataItems(item: CartItem) {
      console.log(item)
      // 创建带goods结构的新对象
      const safeImages = Array.isArray(item.images) ? item.images : []
      const processedGood = {
        id: item.id,
        // 使用安全处理后的 images
        images: safeImages,
        // 使用逻辑或确保布尔值类型安全
        is_favorited: !!item.is_favorited,
        // 数值处理更严谨
        max_origin_price: Number(item.max_origin_price) || 0,
        min_price: Number(item.min_price) || 0,
        name: item.name?.trim() || '未命名商品',
        img: safeImages[0] || '',
        url: item.url || '',
        // 优化随机 hover 图逻辑
        imgHover: safeImages.length > 1
          ? safeImages[Math.floor(Math.random() * (safeImages.length - 1)) + 1]
          : safeImages[0] || '',

      }
      const processedItem = {
        ...item,  // 保留原始字段
        goods: [processedGood]
      }
      // 1. 过滤掉已存在的相同 ID 项
      this.detailDataItems = this.detailDataItems.filter(
        i => i.id !== processedItem.id
      )
      // 2. 将新记录添加到数组开头（保持最新在最前）
      this.detailDataItems.unshift(processedItem)
      //取出里面的 id,images,is_favorited,max_origin_price,min_price,name

      const MAX_HISTORY = 10
      if (this.detailDataItems.length > MAX_HISTORY) {
        this.detailDataItems.splice(MAX_HISTORY)
      }
      if (import.meta.env.DEV) {
        console.log('更新后的浏览记录:', JSON.parse(JSON.stringify(this.detailDataItems)))
      }
    },
    // 清空购物车
    clearCart() {
      Modal.confirm({
        content: () => 'Are you sure you want to delete cart?',
        onOk() {
          return new Promise((resolve, reject) => {
            setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
          }).catch(() => console.log('Oops errors!'));
        },
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onCancel() { },
      }).then(async () => {
        this.items = []
        this.detailDataItems = []
        await clearCarts({}).then(() => {
          // console.log('清空成功')
        })
        Session.remove('cartList')
        this.$persist?.() // 兼容插件方案
        // console.log('清空后的购物车:', JSON.parse(JSON.stringify(this.items)))
      })
        .catch(() => {

        })

    },
    //  移除单个商品通过索引删除
    async removeItemByIndex(index: number, id: number) {
      this.items.splice(index, 1)
      await deleteCarts({ id }).then(() => {
      })
      this.$persist?.()
    },

  },

  getters: {
    totalItems: (state) => state.items.reduce((sum, i) => sum + i.qty, 0),

    // 新增商品总价计算（含两位小数）
    totalPrice(): number {
      const rawTotal = this.items.reduce((acc, item) => {
        // 防御性计算：确保数值类型
        const price = Number(item.price) || 0
        const qty = Number(item.qty) || 1 // 数量默认为1
        return acc + (price * qty)
      }, 0)

      // 处理精度并保留两位小数
      return Number(rawTotal.toFixed(2))
    }

  },
  persist: {
    key: 'myapp_cart',
    paths: ['items', 'detailDataItems']
  }
})
